using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

namespace RideMe.Core
{
    public sealed class ProcessExecutor : IDisposable 
    {
        private Process _proc = new Process();

        /// <summary>
        /// Gets or sets the process.
        /// </summary>
        /// <value>The proc.</value>
        public Process Proc
        {
            get { return _proc; }
            set { _proc = value; }
        }

        /// <summary>
        /// Executes the command which starts a given process.
        /// </summary>
        /// <param name="commmandPath">The commmand path.</param>
        /// <param name="arguments">The arguments.</param>
        public void ExecuteCommand(string commandPath, string arguments, bool redirectStandardError)
        {
            // Set UseShellExecute to false for redirection
            _proc.StartInfo.UseShellExecute = false;
            _proc.EnableRaisingEvents = true;

            // Redirect the standard output of the command.  
            // This stream is read asynchronously using an event handler.
            _proc.StartInfo.RedirectStandardOutput = true;

            _proc.StartInfo.RedirectStandardError = redirectStandardError;

            // Redirect standard input as well.  This stream
            // is used synchronously.
            _proc.StartInfo.RedirectStandardInput = true;

            _proc.StartInfo.CreateNoWindow = true;
            _proc.StartInfo.WorkingDirectory = ProjectService.ProjectPath;
            _proc.StartInfo.FileName = commandPath;
            _proc.StartInfo.Arguments = arguments;
            _proc.Start();

            // Start the asynchronous read of the output stream.
            _proc.BeginOutputReadLine();
            //Where applicable, start the reading of the error stream also
            if(redirectStandardError)
                _proc.BeginErrorReadLine();
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            if (_proc != null)
            {
                _proc.Dispose();
            }
        }
    }
}
